<?php
/**
 * 题目链接 https://leetcode.cn/problems/two-sum/description/
 */

class Solution {

    /**
     * 暴力解法 时间复杂度是O(n^2)
     * @param array $nums
     * @param int $target
     * @return array
     */
    public static function twoSum1(array $nums, int $target): array 
    {
        $len = count($nums);
        for ($i = 0; $i < $len - 1; $i++) { 
            for ($j = $i + 1; $j < $len; $j++) { 
                if ($nums[$i] + $nums[$j] == $target) {
                    return [$i, $j];
                }
            }
        }
        return [];
    }

    /**
     * 利用array_search 时间复杂度是O(log2n)
     * @param array $nums
     * @param int $target
     * @return array
     */
    public static function twoSum2(array $nums, int $target): array 
    {
        $len = count($nums);
        for ($i=0; $i < $len; $i++) { 
            $leave = $target - $nums[$i];
            $index = array_search($leave, $nums);
            if ($index !== false && $index != $i) {
                return [$i, $index];
            }
        }
        return [];
    }

    /**
     * 利用哈希表 时间复杂度是O(n)
     * @param array $nums
     * @param int $target
     * @return array
     */
    public static function twoSum(array $nums, int $target): array 
    {
        $map = [];
        foreach ($nums as $key => $value) {
            $leave = $target - $value;
            if (isset($map[$leave])) {
                return [$key, $map[$leave]];
            } else {
                $map[$value] = $key;
            }
        }
        return [];
    }
}

$test = [
    [[2,7,11,15], 9],
    [[3,2,4], 6],
    [[3,3], 6],
];
foreach ($test as $key => $value) {
    $result = Solution::twoSum($value[0], $value[1]);
    print_r($result);
}